# -*- encoding: utf-8 -*-

import requests
import json

class Message():
    def __init__(self, secret, company_id, agent_id) -> None:
        self.secret = secret
        self.company_id = company_id
        self.agent_id = agent_id
        pass

    def getToken(self):
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}"
        get_req = requests.get(url=url.format(self.company_id, self.secret))
        access_token = get_req.json().get('access_token')

        return access_token

    def sendMsg(self, text):
        # obtain token using Wechat API
        token = self.getToken()
        url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type=image'.format(token)


        # send message
        url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+token
        data = {
            "touser" : '@all',
            "msgtype" : "text",
            "agentid" : self.agent_id,
            "text" : {
                    "content" : text
                },
            "safe" : "0"
        }
        result = requests.post(url=url, data=json.dumps(data))
        err_msg = result.json()['errmsg']

        if err_msg == "ok":
            send_feedback = True
        else:
            send_feedback = False

        return send_feedback


